module repository.user;

import models.user : User;
import database.mydb;

/** 
 * 通过用户名获取用户
 * Params:
 *   username = string
 * Returns: User
 */
User getUserByUserName(string username)
{
    User user = dbsess.createQuery("FROM User WHERE username=:Name")
        .setParameter("Name", username).uniqueResult!User();
    return user;
}

/** 
 * 通过用户id获取用户
 * Params:
 *   userId = long
 * Returns: User
 */
User getUserById(long userId)
{
    User user = dbsess.createQuery("FROM User WHERE id=:userId")
        .setParameter("userId", userId).uniqueResult!User();

    return user;
}

/** 
 * 获取全部用户
 * Returns: User[]
 */
User[] getAllUsers()
{
    return dbsess.createQuery("FROM User ORDER BY id").list!User();
}

/** 
 * 删除用户
 * Params:
 *   userId = long
 * Returns: bool
 */
bool deleteUserById(long userId)
{
    User user = dbsess.createQuery("FROM User WHERE id=:userId")
        .setParameter("userId", userId).uniqueResult!User();
    if (user is null)
    {
        return false;
    }
    dbsess.remove(user);
    return true;
}

/** 
 * 批量删除
 * Params:
 *   userIds = long[]
 * Returns: bool
 */
bool deleteUserByIds(long[] userIds)
{
    foreach (uid; userIds)
    {
        User user = dbsess.createQuery("FROM User WHERE id=:userId")
            .setParameter("userId", uid).uniqueResult!User();
        if (user is null)
        {
            continue;
        }
        dbsess.remove(user);
    }

    return true;
}

/** 
 * 添加用户
 * Params:
 *   newUser = User
 * Returns: bool
 */
bool doAddUser(User newUser)
{
    auto res = dbsess.save(newUser);
    if (!res.hasValue || res <= 0)
    {
        return false;
    }
    return true;
}

/** 
 * 重置密码
 * Params:
 *   userId = long
 *   newPassword =  string
 * Returns: bool
 */
bool resetPwd(long userId, string newPassword)
{
    import utils.common;

    User user = dbsess.createQuery("FROM User WHERE id=:userId")
        .setParameter("userId", userId).uniqueResult!User();
    if (user is null)
    {
        return false;
    }
    user.password = toSHA256String(newPassword);
    dbsess.update(user);
    return true;
}

/** 
 * 修改用户状态
 * Params:
 *   userId = long
 *   status = int
 * Returns: bool
 */
bool setUserStatus(long userId, int status)
{
    import std.algorithm : canFind, map;
    import std.array : array;

    auto user = getUserById(userId);
    if (user is null)
    {
        return false;
    }
    string[] roleCodes = user.roles.map!(x => x.code)().array();
    if (status == 0 && canFind(roleCodes, "ADMIN"))
    {
        return false;
    }

    user.status = status;
    dbsess.update(user);
    return true;
}
